package com.itjiange.springbootinit.mq;

import com.rabbitmq.client.*;

public class FanoutConsumer {
    private static final String EXCHANGE_NAME = "test_exchange_fanout";
    private static final String TASK_QUEUE_NAME1 = "小王的任务";
    private static final String TASK_QUEUE_NAME2 = "小李的任务";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("154.8.205.195");
        factory.setUsername("itjiange");
        factory.setPassword("123456");

        Connection connection = factory.newConnection();
        // 创建两个频道
        Channel channel1 = connection.createChannel();
        Channel channel2 = connection.createChannel();

        // 分别绑定交换机（扇出类型）
        channel1.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
        channel2.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);

        // 创建两个任务队列
        channel1.queueDeclare(TASK_QUEUE_NAME1, true, false, false, null);
        channel2.queueDeclare(TASK_QUEUE_NAME2, true, false, false, null);

        // 绑定队列到交换机
        channel1.queueBind(TASK_QUEUE_NAME1, EXCHANGE_NAME, "");
        channel2.queueBind(TASK_QUEUE_NAME2, EXCHANGE_NAME, "");

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback1 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [小王] Received '" + message + "'");
        };
        channel1.basicConsume(TASK_QUEUE_NAME1, true, deliverCallback1, consumerTag -> {
        });

        DeliverCallback deliverCallback2 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [小李] Received '" + message + "'");
        };
        channel2.basicConsume(TASK_QUEUE_NAME2, true, deliverCallback2, consumerTag -> {
        });
    }
}